# 定义一个装饰器

import time 


# 定义一个装饰器生成器
def timer(threshold):
    def decorator(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            if end_time -  start_time > threshold:
                print(f"{func.__name__} took longer than {threshold}")
            else:
                print(f"{func.__name__} took shorter than {threshold}")
            return result
        return wrapper
    return decorator


# 定义一个函数 使用装饰器
# @timer(2)
def spend_time(seconds):
    time.sleep(seconds)

# spend_time(1)

# 或者使用以下方法
spend_time = timer(2)(spend_time) # 装饰器传入函数的引用/对象
spend_time(1)

# 装饰器用以拓展函数的功能
